
package com.kugou.game.sdk.ui.fragment;

import java.util.UUID;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kugou.game.sdk.adapter.RechargeMoneyGridAdapter;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.PayConstant.ChargeIndexMode;
import com.kugou.game.sdk.entity.PayConstant.ChargeType;
import com.kugou.game.sdk.entity.UnionPayRequestParams;
import com.kugou.game.sdk.ui.activity.RechargeActivity;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;

public class RechargeByUnionFragment extends BaseRechargeFragment implements OnItemClickListener {

    /**
     * 启动activity的请求码
     */
    private final int CODE_START_ACTIVITY_REQUEST = 100;

    /**
     * 开始加载
     */
    private final int MSG_START_LOADING = 1;

    /**
     * 请求支付
     */
    private final int MSG_BACK_REQUEST_PAY = 2;

    /**
     * 标题栏下边的支付金额
     */
    protected TextView mCommonTipsBarMoneyNum;

    /**
     * 充值金额栏、其他金额栏
     */
    private LinearLayout mRechargeLayout, mOtherNumLayout;

    /**
     * 兑换比例
     */
    protected TextView mTvOtherNumTip;

    private GridView mGridView;

    private RechargeMoneyGridAdapter mAdapter;

    private Context mContext;

    private EditText mOtherNumEditText;

    private Button mSummitBtn;

    private int mFixedNum = -1;

    private int mRechargeValue = 10;

    /**
     * 支付订单号
     */
    private String mOrderid = "";

    public static RechargeByUnionFragment getInstance(int num, boolean rechargeYoubi) {
        RechargeByUnionFragment fragment = new RechargeByUnionFragment();
        fragment.mIsRechargeYoubi = rechargeYoubi;
        fragment.mFixedNum = num;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mContext = (RechargeActivity) getActivity();

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initCoupon();
        updateView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        int viewId = Rx.layout.kg_fragment_recharge_by_union;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            viewId = Rx.layout.kg_fragment_recharge_by_union_land;
        }

        return inflater.inflate(viewId, null);
    }

    private int[] moneys = {
            10, 20, 30, 50, 100, 200
    };

    private void initView() {

        int moneyNumId = Rx.id.kg_common_tips_bar_money_num;
        if (moneyNumId != 0) {
            mCommonTipsBarMoneyNum = (TextView) findViewById(moneyNumId);
        }

        mOtherNumEditText = (EditText) findViewById(Rx.id.kg_et_custom_num);
        mSummitBtn = (Button) findViewById(Rx.id.kg_btn_summit);
        mSummitBtn.setText("去银联支付");
        mSummitBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkIsSummit()) {
                    sendEmptyUiMessage(MSG_START_LOADING);
                    sendEmptyBackgroundMessageDelayed(MSG_BACK_REQUEST_PAY, 500);
                    hideSoftInput(mContext);
                    // 发送统计--点击确认支付按钮
                    sendClickConfirmRechargeBtnStatics(ChargeType.TYPE_YIPAY, mRechargeValue);
                }
            }
        });
        mTvOtherNumTip = (TextView) findViewById(Rx.id.kg_pay_other_num_text);
        mRechargeLayout = (LinearLayout) findViewById(Rx.id.kg_layout_recharge_content);
        mOtherNumLayout = (LinearLayout) findViewById(Rx.id.kg_layout_other_money);

        mGridView = (GridView) findViewById(Rx.id.kg_gridview);
        mAdapter = new RechargeMoneyGridAdapter(mContext, moneys, RechargeMoneyGridAdapter.UNIT_YUN);
        mGridView.setAdapter(mAdapter);
        if (mFixedNum > 0) {
            updateFixedMoneyNumTextView();
            return;
        }

        // 恢复上次支付金额
        mAdapter.setmMoneyIndex(0);
        mRechargeValue = moneys[0];

        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            mGridView.setNumColumns(6);
        }
        mGridView.setOnItemClickListener(this);
        mTvOtherNumTip.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mOtherNumLayout.setVisibility(View.VISIBLE);
                mOtherNumEditText.requestFocus();
                if (mAdapter.getmMoneyIndex() != -1) {
                    mAdapter.setmMoneyIndex(-1);
                    mAdapter.notifyDataSetChanged();
                    mRechargeValue = getRechargeValueByEditText(mOtherNumEditText.getText()
                            .toString());
                    updateView();
                }
            }
        });

        mOtherNumEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mOtherNumLayout != null && mOtherNumLayout.getVisibility() == View.VISIBLE) {
                    String value = s.toString().trim();
                    if (AppUtil.checkRechargeValueInput(value) || value.length() == 0) {

                        mRechargeValue = getRechargeValueByEditText(value);
                        updateView();
                    } else {
                        mRechargeValue = 0;
                        if (!TextUtils.isEmpty(value)) {
                            mOtherNumEditText.setText("");
                        }
                    }
                }
            }
        });

        mOtherNumEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showSoftInput();
                } else {
                    hideSoftInput(mContext);
                }
            }
        });
    }

    protected void updateFixedMoneyNumTextView() {
        if (mFixedNum <= 0) {
            return;
        }
        mCommonTipsBarMoneyNum.setVisibility(View.VISIBLE);

        int value = mFixedNum;
        if (mSelectedCoupon != null) {
            value = value - mSelectedCoupon.getMoney();
            if (value < 0)
                value = 0;
        }
        mCommonTipsBarMoneyNum.setText(Html.fromHtml("<font color=#666666>支付：</font>"
                + "<font color=#fd9526>" + value + "元" + "</font>"));
        mRechargeLayout.setVisibility(View.GONE);
        mRechargeValue = mFixedNum;

        mCommonTipsBarMoneyNum
                .setPadding(0, 0, 0, (int) (PADDING_BTN * getResources()
                        .getDisplayMetrics().density));
    }

    /**
     * 从EditText中获取充值的数值
     * 
     * @param value
     * @return
     */
    private int getRechargeValueByEditText(String value) {
        if (!TextUtils.isEmpty(value)) {
            return Integer.valueOf(value);
        } else {
            return 0;
        }
    }

    protected void updateView() {

        updateCouponView(mRechargeValue);

        if (mIsRechargeYoubi) {
            updateCanGotKubiTextView(mRechargeValue, ChargeType.TYPE_YIPAY);
        }
    }

    private boolean checkIsSummit() {
        if (mRechargeValue <= 0) {
            showToast("请输入有效的金额");
            return false;
        }
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mAdapter.getItem(position) == 0) {
            return;
        }

        if (!NetWorkUtil.isNetworkAvailable(mContext)) {
            showToast("请检查您的网络连接");
            return;
        }

        mOtherNumEditText.clearFocus();
        mOtherNumLayout.setVisibility(View.GONE);
        mAdapter.onItemClick(parent, view, position, id);
        mAdapter.notifyDataSetChanged();
        mRechargeValue = (Integer) mAdapter.getItem(position);
        updateView();
    }

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }
        switch (msg.what) {
            case MSG_START_LOADING:
                showLoadingView();
                break;
        }
    }

    /**
     * 发送取消支付的统计
     */
    private void sendCancelRechargeStatics(int recordtype, int errorcode, String errormsg) {
        sendCancelRechargeStatics(ChargeType.TYPE_YIPAY, mRechargeValue, mOrderid, recordtype,
                errormsg);
    }

    /**
     * 显示一些消息提示的确定弹框
     * 
     * @param tips 弹框Message
     */
    private void showNoticeDialog(String tips) {
        if (isDetached()) {
            return;
        }
        final BaseConfirmDialog failedDialog = new BaseConfirmDialog(getActivity());
        failedDialog
                .setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
        failedDialog.setTextGravity(Gravity.CENTER);
        failedDialog.setMessage(TextUtils.isEmpty(tips) ? "" : tips);
        failedDialog.setCancelBtnVisibility(View.GONE);
        failedDialog.setContentGravity(Gravity.CENTER);
        failedDialog.setOKBtnText("知道了");
        failedDialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                failedDialog.dismiss();

            }
        });
        failedDialog.show();
    }

    private void showLayoutRechargeSuccess() {
        if (getOnEventListener() != null) {
            getOnEventListener().onRechargeSuccess(ChargeIndexMode.MODE_UNION, mRechargeValue);
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);
        switch (msg.what) {
            case MSG_BACK_REQUEST_PAY:
                payByUnion("");
                break;
        }
    }

    /**
     * 网银支付请求
     * 
     * @param carType "":表示银联卡; 01:表示借记卡; 02：表示信用卡
     */
    private void payByUnion(String carType) {
        UnionPayRequestParams requestParams = new UnionPayRequestParams();
        mOrderid = SDKControler.createNewOrderId();
        if (mIsRechargeYoubi) {
            // 生成唯一字符串
            mOrderid = UUID.randomUUID().toString();
            requestParams.setDirectCharge(0);
        } else {
            requestParams.setDirectCharge(1);
        }

        User user = UserManager.getInstance().getCurrentUserInternal();
        requestParams.setUserName(user.getAccountName());
        requestParams.setChargeType(ChargeType.TYPE_YIPAY);

        if (mSelectedCoupon != null) {
            requestParams.setCouponId(mSelectedCoupon.getId());
        }

        requestParams.setMoney(mRechargeValue * 100);

        requestParams.setOutOrderId(mOrderid);
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());
        requestParams.setCardtype(carType);
        PayManager.payByUnion(this, CODE_START_ACTIVITY_REQUEST, requestParams);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        /*************************************************
         * 步骤3：处理银联手机支付控件返回的支付结果
         ************************************************/
        if (data == null || resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case CODE_START_ACTIVITY_REQUEST: {

                /*
                 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
                 */
                int payResult = data.getExtras().getInt("pay_result", 0);
                String resultDescription = data.getStringExtra("result_description");
                switch (payResult) {
                    case 1:
                        // 支付成功
                        showLayoutRechargeSuccess();

                        sendRechargeSuccessEvent(mOrderid, ChargeType.TYPE_YIPAY, mRechargeValue);

                        break;
                    case 2:
                        // 支付失败
                        hideLoadingView();
                        if (!TextUtils.isEmpty(resultDescription)) {
                            showNoticeDialog(resultDescription);
                        }

                        canelRecharge();
                        // 发送支付错误操作统计
                        sendCancelRechargeStatics(1, -10000, "银联支付错误");
                        break;
                    case 3:
                        // 用户取消了支付
                        hideLoadingView();
                        if (!TextUtils.isEmpty(resultDescription)) {
                            showNoticeDialog(resultDescription);
                        }

                        canelRecharge();
                        // 发送取消支付操作统计
                        sendCancelRechargeStatics(0, 0, "取消银联支付");
                        break;

                    default:
                        break;
                }
                break;

            }
        }

    }

}
